package com.zjj.reggie.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.zjj.reggie.Utils.SMSUtils;
import com.zjj.reggie.Utils.ValidateCodeUtils;
import com.zjj.reggie.common.R;
import com.zjj.reggie.entity.User;
import com.zjj.reggie.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@Slf4j
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private RedisTemplate redisTemplate;


    /**
     * 发送手机验证码
     * @param user
     * @return
     */
    @PostMapping("/sendMsg")
    public R<String> sendMsg(@RequestBody User user, HttpSession session) {

        //获取手机号码
        String phone = user.getPhone();
        log.info("手机号码："+phone);
        if (StringUtils.isNotEmpty(phone)){
        //生成验证码
        String  code = ValidateCodeUtils.generateValidateCode(4).toString();
        log.info("验证码："+code);
        //调用短信接口发送验证码
//            SMSUtils.sendMessage("瑞吉外卖","SMS_465926529",phone, code);
        //保存验证码到Session
//        session.setAttribute(phone, code);

        //将生成的验证码缓存到redis中，并设置过期时间5分钟
        redisTemplate.opsForValue().set(phone, code, 5, TimeUnit.MINUTES);

        //返回成功信息
        return R.success("验证码发送成功");
        }

        return R.error("手机号码不能为空");
    }

    /**
     * 移动端用户登录
     * @param map
     * @return
     */
    @PostMapping("/login")
    public R<User> login(@RequestBody Map map, HttpSession session) {

        log.info("用户登录："+map.toString());
        //获取手机号码
        String phone = map.get("phone").toString();
        //获取验证码
        String code = map.get("code").toString();
        //从Session中获取验证码
//        Object codeInSession = session.getAttribute(phone);

        //从redis中获取验证码
        Object codeInRedis =  redisTemplate.opsForValue().get(phone);



        //判断验证码是否正确
        if (codeInRedis!= null && codeInRedis.equals(code)){
        //验证码正确，登录成功

        //登录成功，判断当前手机号是否为新用户，如果是，则注册用户
            LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(User::getPhone, phone);
            User user = userService.getOne(queryWrapper);
            if (user == null){
                //登录成功，判断当前手机号是否为新用户，如果是，则注册用户
                user = new User();
                user.setPhone(phone);
                user.setStatus(1);
                userService.save(user);
            }
            //登录成功，就删除session中的验证码
//            session.removeAttribute(phone);;

            //删除redis中的验证码
            redisTemplate.delete(phone);

            //登录成功，更新用户登录信息
            session.setAttribute("user", user.getId());

            //登录成功，返回用户信息

            return R.success(user);
        }

        return R.error("验证码错误");
    }

    /**
     * 用户退出登录
     */
    @PostMapping("/loginout")
    public R<String> logout(HttpServletRequest request) {
        //清除用户登录信息
        request.getSession().removeAttribute("user");
        return R.success("退出登录成功");
    }

}
